package com.ty.day8;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @create : 2023/12/1 9:38
 */
public class SocketServer {
    private ServerSocket serverSocket;
    public SocketServer() {
        try {
            System.out.println("开始初始化");
            //端口号，886，客户端通过ip+端口才能通信，且端口号不能冲突
            serverSocket = new ServerSocket(8886);
            System.out.println("初始化完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //启动服务器，等待客户端来连接，提供服务
    public void start() throws IOException {
        //一直监听
        while (true) {
            System.out.println("等待连接");
            //client是客户端的socket对象，内容都在对象中
            Socket client = serverSocket.accept();
            //客户端地址
            InetAddress address = client.getInetAddress();
            //客户端的ip，包含在地址中
            String ip = address.getHostAddress();
            //客户端的port
            int clientPort = client.getPort();
            System.out.println(ip+":" +clientPort+ "来了");
            //io操作，客户端发送的信息等
            InputStream is = client.getInputStream();
            //包装输入流
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String s;
            while ((s= br.readLine())!=null){
                System.out.println(s);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        SocketServer server = new SocketServer();
        server.start();
    }
}